//
//  AppDelegate.swift
//  SinaWeibo
//
//  Created by apple on 15/11/8.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    
    
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.makeKeyAndVisible()
        window?.rootViewController = defaultrootViewController()
        
        setUPThemeColor()
        
        //判断是否是新版本
        
       //注册通知
        registerNotification()
        
        return true
    }
    
    func registerNotification () {
        
        //object 代表接受哪家发出的通知 nil 表示通吃 
       NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchToRootVC:", name: appSwitchToViewController, object: nil)
    }
    
    @objc private func switchToRootVC(note: NSNotification) {
        
        print(note)
        
        if (note.object as? String) != nil {
            
            window?.rootViewController = WelcomeViewController()
        }else {
            window?.rootViewController = MainController()
        }
    }

    func setUPThemeColor () {
        
        UINavigationBar.appearance().tintColor = themeColor
        UITabBar.appearance().tintColor = themeColor
    }
    
    //根据版本号 判断跳转的控制器 
    func defaultrootViewController () -> UIViewController {
        
        
        return isNewVersion() ? NewFeatureViewController() : WelcomeViewController()
    }
    
    //判断是否是新版本
    private func isNewVersion () -> Bool{
        
        //获取当前的版本号
        let versionStr = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        
        let versionNum = Double(versionStr)
        
        //获取旧版本 一般保存在沙盒中
        let key = "oldVersion"
        let lastVersion = NSUserDefaults.standardUserDefaults().doubleForKey(key)
        
        //保存新版本
        NSUserDefaults.standardUserDefaults().setDouble(versionNum!, forKey: key)
        //同步
        NSUserDefaults.standardUserDefaults().synchronize()
        
        //比较
        return versionNum! > lastVersion
        
        
    }
}

